<template>
  <div class="workflow-execute">
    <!-- 顶部导航 -->
    <div class="page-header">
      <div class="left">
        <el-button icon="Back" @click="goBack">返回</el-button>
        <el-divider direction="vertical" />
        <h2>执行工作流 - {{ workflow?.name }}</h2>
      </div>
      <div class="right">
        <el-button-group>
          <el-button @click="goBack">取消</el-button>
          <el-button 
            type="primary"
            :loading="executing"
            @click="execute"
          >
            开始执行
          </el-button>
        </el-button-group>
      </div>
    </div>

    <div class="main-content">
      <div class="content-wrapper">
        <!-- 左侧参数面板 -->
        <div class="params-panel">
          <el-card class="params-card">
            <template #header>
              <div class="card-header">
                <span>参数配置</span>
                <el-button 
                  link 
                  type="primary"
                  @click="resetParams"
                >
                  重置参数
                </el-button>
              </div>
            </template>

            <param-form
              v-model="params"
              :template="workflow"
              @change="handleParamsChange"
            />
          </el-card>
        </div>

        <!-- 右侧结果面板 -->
        <div class="result-panel">
          <!-- 执行状态 -->
          <el-card v-if="executing || result" class="status-card">
            <template #header>
              <div class="card-header">
                <span>执行状态</span>
                <el-tag :type="statusType">{{ statusText }}</el-tag>
              </div>
            </template>

            <div v-if="executing" class="executing-status">
              <el-progress 
                :percentage="progress" 
                :status="progressStatus"
              />
              <p class="status-text">{{ statusMessage }}</p>
            </div>

            <div v-else-if="result" class="result-status">
              <div class="time-info">
                <div class="item">
                  <label>开始时间：</label>
                  <span>{{ formatDate(result.start_time) }}</span>
                </div>
                <div class="item">
                  <label>结束时间：</label>
                  <span>{{ formatDate(result.end_time) }}</span>
                </div>
                <div class="item">
                  <label>耗时：</label>
                  <span>{{ formatDuration(result.duration) }}</span>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 生成结果 -->
          <el-card v-if="result?.output" class="result-card">
            <template #header>
              <div class="card-header">
                <span>生成结果</span>
                <div class="actions">
                  <el-button-group>
                    <el-button 
                      icon="Download"
                      @click="downloadResult"
                    >
                      下载
                    </el-button>
                    <el-button 
                      icon="Share"
                      @click="shareResult"
                    >
                      分享
                    </el-button>
                  </el-button-group>
                </div>
              </div>
            </template>

            <div class="result-content">
              <!-- 图片结果 -->
              <template v-if="['text2img', 'img2img'].includes(workflow?.category)">
                <el-image 
                  :src="result.output"
                  fit="contain"
                  :preview-src-list="[result.output]"
                />
              </template>

              <!-- 视频结果 -->
              <template v-else-if="['text2video', 'img2video'].includes(workflow?.category)">
                <video 
                  :src="result.output"
                  controls
                  class="video-player"
                />
              </template>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useWorkflowStore } from '@/stores/workflow'
import ParamForm from '@/components/ParamForm.vue'
import { formatDate, formatDuration } from '@/utils/format'

const route = useRoute()
const router = useRouter()
const workflowStore = useWorkflowStore()

// 工作流数据
const workflow = ref<any>(null)
const params = ref({})
const executing = ref(false)
const progress = ref(0)
const result = ref<any>(null)
const statusMessage = ref('')

// 计算属性
const statusType = computed(() => {
  if (executing.value) return 'warning'
  if (result.value?.error) return 'danger'
  if (result.value) return 'success'
  return 'info'
})

const statusText = computed(() => {
  if (executing.value) return '执行中'
  if (result.value?.error) return '执行失败'
  if (result.value) return '执行完成'
  return '未执行'
})

const progressStatus = computed(() => {
  if (progress.value >= 100) return 'success'
  return ''
})

// 方法
const goBack = () => {
  router.push('/workflow/list')
}

const resetParams = () => {
  params.value = workflow.value?.default_params || {}
}

const handleParamsChange = () => {
  // 清除之前的结果
  result.value = null
}

// 执行工作流
const execute = async () => {
  try {
    executing.value = true
    progress.value = 0
    result.value = null
    statusMessage.value = '正在初始化...'

    // 启动执行
    const taskId = await workflowStore.executeWorkflow(
      workflow.value.id,
      params.value
    )

    // 轮询进度
    await pollProgress(taskId)

    // 获取结果
    result.value = await workflowStore.getExecuteResult(taskId)
    ElMessage.success('执行完成')
  } catch (error: any) {
    ElMessage.error(error.message || '执行失败')
    result.value = { error }
  } finally {
    executing.value = false
  }
}

// 轮询进度
const pollProgress = async (taskId: string) => {
  while (true) {
    const status = await workflowStore.getExecuteStatus(taskId)
    progress.value = status.progress
    statusMessage.value = status.message

    if (status.progress >= 100 || status.error) {
      break
    }

    await new Promise(resolve => setTimeout(resolve, 1000))
  }
}

// 下载结果
const downloadResult = () => {
  if (!result.value?.output) return
  
  const link = document.createElement('a')
  link.href = result.value.output
  link.download = `result_${Date.now()}.${getFileExtension()}`
  link.click()
}

// 获取文件扩展名
const getFileExtension = () => {
  const category = workflow.value?.category
  if (['text2video', 'img2video'].includes(category)) {
    return 'mp4'
  }
  return 'png'
}

// 分享结果
const shareResult = () => {
  // TODO: 实现分享功能
  ElMessage.info('分享功能开发中')
}

// 初始化
const init = async () => {
  try {
    const id = route.params.id as string
    workflow.value = await workflowStore.getWorkflow(id)
    params.value = workflow.value.default_params || {}
  } catch (error) {
    ElMessage.error('获取工作流信息失败')
    router.push('/workflow/list')
  }
}

onMounted(() => {
  init()
})
</script>

<style scoped>
.workflow-execute {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-header {
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-light);
  background: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header .left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-header h2 {
  margin: 0;
}

.main-content {
  flex: 1;
  padding: 20px;
  background: var(--el-bg-color-page);
  overflow: auto;
}

.content-wrapper {
  display: flex;
  gap: 20px;
  height: 100%;
}

.params-panel {
  width: 400px;
  flex-shrink: 0;
}

.result-panel {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.params-card,
.status-card,
.result-card {
  height: fit-content;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.executing-status {
  padding: 20px 0;
}

.status-text {
  margin: 10px 0 0;
  color: #666;
  text-align: center;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.time-info .item {
  display: flex;
  gap: 10px;
}

.time-info label {
  color: #666;
  width: 80px;
}

.result-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.result-content .el-image {
  max-width: 100%;
  max-height: 600px;
}

.video-player {
  max-width: 100%;
  max-height: 600px;
}
</style> 